﻿<%@ WebHandler Language="C#" Class="ZSTransactionHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

public class ZSTransactionHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    QulityCheckBusiness Q_check = new QulityCheckBusiness();
    TransactionBusiness m_Tran = new TransactionBusiness();
    uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    StringBuilder result = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetEmployees"://人员查询
                    GetEmployees(context);
                    break;
                case "GetTransaction"://查询事务数据--分页
                    GetTransaction(context);
                    break;
                case "InsertTransaction"://插入事务
                    InsertTransaction(context);
                    break;
                case "DeleteTransaction"://删除事务
                    DeleteTransaction(context);
                    break;
                case "RecieveTransaction"://接收事务
                    RecieveTransaction(context);
                    break;
                case "FinishTransaction"://完成事务
                    FinishTransaction(context);
                    break;
                case"NoFinishTransaction":
                    NoFinishTransaction(context);
                    break;   
                case "SumTransaction"://事务数据统计
                    SumTransaction(context);
                    break;    
                case "GetTreeData":
                    GetTreeData(context);
                    break;
                case "GetUserListData":
                    GetUserListData(context);
                    break;
                case "GetMfgOrderLackMaterials"://订单缺件查询
                    GetMfgOrderLackMaterials(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 查询所有责任人
    /// </summary>
    /// <param name="context"></param>
    protected void GetEmployees(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        string Name = context.Request["Name"].ToString();
        var para = new Dictionary<String, String>();
        para.Add("Name", Name);
        result.DBTable = Q_check.GetEmployees(para);//AddDutyUnit();
        result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "" : "根据条件匹配不到相应责任人信息";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetTransaction(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("TransactionType", dt.Rows[0]["TransactionType"].ToString());
        para.Add("MainUnit", dt.Rows[0]["MainUnit"].ToString());
        para.Add("Status", dt.Rows[0]["Status"].ToString());
        para.Add("startedate", dt.Rows[0]["startedate"].ToString());
        para.Add("enddate", dt.Rows[0]["enddate"].ToString());
        para.Add("PageSize", pageSize);
        para.Add("CurrentPageIndex", pageNumber);
        uMESProcessResult result = m_Tran.GetTransaction(para);
        foreach (DataRow row in result.DBTable.Rows)
        {
            if (row["MAINEMPLOYEEID"].ToString().Split(',').Length > 0)
            {
                var MAINEMPLOYEE = string.Empty;
                foreach (var id in row["MAINEMPLOYEEID"].ToString().Split(','))
                {
                    MAINEMPLOYEE += m_CommonObj.GetEmployeeByEmployeeID(id).Rows[0]["FULLNAME"].ToString() + ",";
                }
                row["MAINEMPLOYEE"] = MAINEMPLOYEE.TrimEnd(',');
            }
        }
        result.ReturnData = m_UserInfo.EmployeeID.ToString();
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void InsertTransaction(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var para = new Dictionary<string, string>();
        var TRANSACTIONID = dt.Rows[0]["TRANSACTIONID"].ToString();
        para.Add("TRANSACTIONID", string.IsNullOrWhiteSpace(TRANSACTIONID) ? Guid.NewGuid().ToString() : TRANSACTIONID);//唯一ID
        para.Add("TRANSACTIONTYPE", dt.Rows[0]["TRANSACTIONTYPE"].ToString());
        para.Add("TRANSACTIONCONTENT", dt.Rows[0]["TRANSACTIONCONTENT"].ToString());
        para.Add("HANDLEITEM", dt.Rows[0]["HANDLEITEM"].ToString());
        para.Add("DELIVERABLES", dt.Rows[0]["DELIVERABLES"].ToString());
        para.Add("MAINUNIT", dt.Rows[0]["MAINUNIT"].ToString());
        para.Add("MAINEMPLOYEEID", dt.Rows[0]["MAINEMPLOYEEID"].ToString());
        para.Add("COORDINATEUNIT", dt.Rows[0]["COORDINATEUNIT"].ToString());
        para.Add("COORDINATEEMPLOYEEID", dt.Rows[0]["COORDINATEEMPLOYEEID"].ToString());
        para.Add("REQUIREDFINISHDATE", dt.Rows[0]["REQUIREDFINISHDATE"].ToString());
        para.Add("CREATEEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
        para.Add("TRANSACTIONCATEGORY", dt.Rows[0]["TRANSACTIONCATEGORY"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.Result = string.IsNullOrWhiteSpace(TRANSACTIONID) ? m_Tran.InsertTransaction(para) : m_Tran.UpdateTransaction(para);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void DeleteTransaction(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("IDS", context.Request["ids"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_Tran.DeleteTransaction(para);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void RecieveTransaction(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("TRANSACTIONID", context.Request["ids"].ToString());
        para.Add("RECIEVEEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_Tran.UpdateTransaction(para);
        result.Message = result.Result ? "接收成功" : "接收失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void FinishTransaction(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("TRANSACTIONID", context.Request["ids"].ToString());
        para.Add("ActualFinishDate", "");
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_Tran.UpdateTransaction(para);
        result.Message = result.Result ? "完成操作成功" : "完成操作失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void NoFinishTransaction(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("TRANSACTIONID", context.Request["ids"].ToString());
        para.Add("STATUS", "3");
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_Tran.UpdateTransaction(para);
        result.Message = result.Result ? "未完成操作成功" : "未完成操作失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    

    private void SumTransaction(HttpContext context) 
    {
        var sql = @"SELECT a.Tname,nvl(FINISHCOUNT,0)FINISHCOUNT,nvl(NOFINISHCOUNT,0) NOFINISHCOUNT,nvl(processCOUNT,0) processCOUNT,nvl(TOTAL,0) TOTAL
            FROM (
            SELECT 0 Tid,'技术' Tname FROM dual
            UNION SELECT 1 Tid,'质量' Tname FROM dual
            UNION SELECT 2 Tid,'生产' Tname FROM dual
            UNION SELECT 3 Tid,'AEOS' Tname FROM dual
            UNION SELECT 4 Tid,'保密' Tname FROM dual
            UNION SELECT 5 Tid,'财务' Tname FROM dual
            UNION SELECT 6 Tid,'党建' Tname FROM dual
            UNION SELECT 7 Tid,'行政' Tname FROM dual
            UNION SELECT 8 Tid,'其他' Tname FROM dual
            ) a LEFT JOIN (
            SELECT COUNT(decode(z.STATUS,2,1,null)) FINISHCOUNT,COUNT(decode(z.STATUS,3,1,null)) NOFINISHCOUNT,COUNT(decode(z.STATUS,1,1,null)) processCOUNT,
            COUNT(decode(z.STATUS,2,1,null))+COUNT(decode(z.STATUS,3,1,null))+COUNT(decode(z.STATUS,1,1,null)) TOTAL,
            DECODE(z.TRANSACTIONCATEGORY,NULL,8,z.TRANSACTIONCATEGORY) TRANSACTIONCATEGORY 
            FROM ZSTRANSACTIONINFO z GROUP BY DECODE(z.TRANSACTIONCATEGORY,NULL,8,z.TRANSACTIONCATEGORY)
            )b ON a.Tid=b.TRANSACTIONCATEGORY
            ORDER BY a.Tid";
        var dt = DatabaseHelper.Query_ReturnDatTable(sql);
        var sql1 = @"SELECT COUNT(decode(z.STATUS,2,1,null)) value ,'已完成' name FROM ZSTRANSACTIONINFO z 
                UNION SELECT COUNT(decode(z.STATUS,3,1,null)) value ,'未完成' name FROM ZSTRANSACTIONINFO z 
                UNION SELECT COUNT(decode(z.STATUS,1,1,null)) value ,'进行中' name FROM ZSTRANSACTIONINFO z ";
        var dt1 = DatabaseHelper.Query_ReturnDatTable(sql1);
        
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = dt;
        result.ReturnData = dt1;
        context.Response.Write(JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings{ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()}));
    }
    
    
    
    
    private void GetTreeData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var userSql = @"select e.fullname,e.employeename,e.employeeid from roledef ro 
                    left JOIN employeerole erl ON erl.roleid=ro.roleid
                    left JOIN employee e on e.employeeid=erl.employeeid
                    where ro.rolename like '事务专员'";
        var dt = DatabaseHelper.Query_ReturnDatTable(userSql);
        result.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private void GetTreeDatad(HttpContext context)
    {
        uMESProcessResult resultP = new uMESProcessResult();
        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
        var datatable = new DataTable();
        datatable.Columns.Add("id");
        datatable.Columns.Add("text");
        datatable.Columns.Add("pid");
        //var factoryDt = m_CommonObj.GetFactory(new Dictionary<string,string>());
        //var fdv = factoryDt.DefaultView;
        //fdv.RowFilter = "FACTORYID='"+m_UserInfo.FactoryID.ToString()+"'";
        //factoryDt = fdv.ToTable();
        //foreach (DataRow row in factoryDt.Rows) {
        //    DataRow Nrow = datatable.NewRow();
        //    Nrow["id"] = row["FACTORYID"].ToString();
        //    Nrow["text"] = row["FACTORYNAME"].ToString();
        //    Nrow["pid"] = row["ENTERPRISEID"].ToString();
        //    datatable.Rows.Add(Nrow);
        var workCneter = m_CommonObj.GetWorkCenterByFacoryID(m_UserInfo.FactoryID.ToString(), true);
        foreach (DataRow wrow in workCneter.Rows)
        {
            DataRow Nwrow = datatable.NewRow();
            Nwrow["id"] = wrow["WORKCENTERID"].ToString();
            Nwrow["text"] = wrow["WORKCENTERNAME"].ToString();
            Nwrow["pid"] = m_UserInfo.FactoryID.ToString(); //row["FACTORYID"].ToString();
            datatable.Rows.Add(Nwrow);
        }
        //}
        GetTreeJsonByTable(datatable, "id", "text", "pid", m_UserInfo.FactoryID.ToString());
        resultP.ReturnData = result.ToString();
        context.Response.Write(result.ToString());
    }


    private void GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
    {
        result.Append(sb.ToString());
        sb.Clear();
        if (tabel.Rows.Count > 0)
        {
            sb.Append("[");
            string filer = string.Format("{0}='{1}'", rela, pId);
            DataRow[] rows = tabel.Select(filer);
            if (rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\"");
                    if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                    {
                        sb.Append(",\"state\":\"closed\",\"children\":");
                        GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                        result.Append(sb.ToString());
                        sb.Clear();
                    }
                    result.Append(sb.ToString());
                    sb.Clear();
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            result.Append(sb.ToString());
            sb.Clear();
        }
    }

    private void GetUserListData(HttpContext context)
    {
        var ids = context.Request["ids"].ToString();
        var sqlStr = "SELECT e.FULLNAME NAME,e.EMPLOYEEID ID FROM EMPLOYEE e LEFT JOIN Sessionvalues sv ON e.employeeid=sv.employeeid WHERE sv.workcenterid IN ('{0}') oR sv.factoryid IN ('{0}') order by e.FULLNAME";
        var dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sqlStr, ids.Replace(",", "','")));
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 订单缺件查询
    /// </summary>
    /// <param name="context"></param>
    private void GetMfgOrderLackMaterials(HttpContext context)
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        //UpdateMfgOrderStatus();//状态修改 2023-05-04 去掉状态修改，直接查询
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = getMfgOrderLMSql(context);
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private string getMfgOrderLMSql(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var sql = @"SELECT u.ATTRIBUTEVALUE EngineNo,td.* FROM T_DDQLT td  
         LEFT JOIN MFGORDER m  ON m.MFGORDERNAME=td.AUFNR
         LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
                where 1=1  ";//and mes_status='1'
        if (!string.IsNullOrWhiteSpace(dt.Rows[0]["AUFNR"].ToString()))
        {
            sql += " and AUFNR like '%" + dt.Rows[0]["AUFNR"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dt.Rows[0]["IDNRK"].ToString()))
        {
            sql += " and IDNRK like '%" + dt.Rows[0]["IDNRK"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dt.Rows[0]["GSTRP"].ToString()))
        {
            sql += " and GSTRP>='" +Convert.ToDateTime(dt.Rows[0]["GSTRP"].ToString()).ToString("yyyyMMdd") + "'";
        }
        if (!string.IsNullOrWhiteSpace(dt.Rows[0]["GLTRP"].ToString()))
        {
            sql += " and GLTRP<='" + Convert.ToDateTime(dt.Rows[0]["GLTRP"].ToString()).ToString("yyyyMMdd") + "'";
        }
        return sql;
    }
    /// <summary>
    /// 
    /// </summary>
    private void UpdateMfgOrderStatus()
    {
        var sql = @"SELECT * FROM T_DDQLT td  where 1=1 ";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql + " and td.mes_status='0'");
        DataTable dt1 = DatabaseHelper.Query_ReturnDatTable(sql + "and td.mes_status='1'");
        ArrayList arr = new ArrayList();
        if (dt.Rows.Count > 0 && dt1.Rows.Count == 0)//只有0状态数据，0改为1
        {
            arr.Add("UPDATE T_DDQLT set mes_status=1 where mes_status='0'");
        }
        else if (dt.Rows.Count > 0 && dt1.Rows.Count > 0)//有0和1：先删除1，再把0改为1
        {
            arr.Add("delete from T_DDQLT where mes_status='1'");
            arr.Add("UPDATE T_DDQLT set mes_status=1 where mes_status='0'");
        }
        else { }//全是1或表数据为空，不做处理
        if (arr.Count > 0)
        {
            DatabaseHelper.ExecuteSqlListTran(arr);
        }
    }
}